package org.jeecg.modules.analysis.trend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.analysis.genealogy.entity.Genealogy;
import org.jeecg.modules.analysis.genealogy.service.IGenealogyService;
import org.jeecg.modules.analysis.trend.dto.TechnologyDTO;
import org.jeecg.modules.analysis.trend.dto.TrendQueryDTO;
import org.jeecg.modules.analysis.trend.service.ITrendAnalysisService;
import org.jeecg.modules.analysis.trend.vo.TechnologyTrendVO;
import org.jeecg.modules.analysis.trend.vo.TrendQueryResultVO;
import org.jeecg.modules.demo.patent.entity.Patent;
import org.jeecg.modules.demo.patent.service.IPatentService;
import org.jeecg.modules.manage.technology.entity.PatentGenealogy;
import org.jeecg.modules.manage.technology.service.IPatentGenealogyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 趋势分析服务实现类
 * @Author: jeecg-boot
 * @Date: 2025-11-04
 * @Version: V1.0
 */
@Service
@Slf4j
public class TrendAnalysisServiceImpl implements ITrendAnalysisService {

    @Autowired
    private IGenealogyService genealogyService;

    @Autowired
    private IPatentService patentService;

    @Autowired
    private IPatentGenealogyService patentGenealogyService;

    @Override
    public List<TechnologyDTO> getAllTechnologyList() {
        log.info("开始获取所有技术分类列表");
        
        try {
            // 获取所有技术分类
            QueryWrapper<Genealogy> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("parent_id", "sort", "name");
            List<Genealogy> genealogyList = genealogyService.list(queryWrapper);
            
            if (CollUtil.isEmpty(genealogyList)) {
                log.warn("未查询到技术分类数据");
                return new ArrayList<>();
            }
            
            // 转换为DTO对象
            List<TechnologyDTO> technologyDTOList = genealogyList.stream()
                    .map(this::convertToTechnologyDTO)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            
            log.info("成功获取技术分类列表，共{}条", technologyDTOList.size());
            return technologyDTOList;
            
        } catch (Exception e) {
            log.error("获取技术分类列表失败", e);
            throw new RuntimeException("获取技术分类列表失败：" + e.getMessage());
        }
    }

    @Override
    public TrendQueryResultVO getTechnologyTrend(TrendQueryDTO queryDTO) {
        log.info("开始查询技术申请趋势，参数：{}", queryDTO);
        
        try {
            TrendQueryResultVO resultVO = new TrendQueryResultVO();
            
            // 设置查询参数
            TrendQueryResultVO.QueryParamsVO queryParamsVO = new TrendQueryResultVO.QueryParamsVO();
            BeanUtil.copyProperties(queryDTO, queryParamsVO);
            resultVO.setQueryParams(queryParamsVO);
            
            // 查询趋势数据
            List<TechnologyTrendVO> trendDataList = queryTrendDataByTechnologyIds(
                    queryDTO.getTechnologyIds(), 
                    queryDTO.getStartYear(), 
                    queryDTO.getEndYear()
            );
            
            resultVO.setTrendDataList(trendDataList);
            
            // 计算统计信息
            TrendQueryResultVO.StatisticsVO statisticsVO = calculateStatistics(
                    trendDataList, 
                    queryDTO.getStartYear(), 
                    queryDTO.getEndYear()
            );
            resultVO.setStatistics(statisticsVO);
            
            log.info("成功查询技术申请趋势，共{}个技术分类", trendDataList.size());
            return resultVO;
            
        } catch (Exception e) {
            log.error("查询技术申请趋势失败", e);
            throw new RuntimeException("查询技术申请趋势失败：" + e.getMessage());
        }
    }

    /**
     * 根据技术分类ID列表查询趋势数据
     */
    private List<TechnologyTrendVO> queryTrendDataByTechnologyIds(List<String> technologyIds, 
                                                                  Integer startYear, 
                                                                  Integer endYear) {
        List<TechnologyTrendVO> trendDataList = new ArrayList<>();
        
        for (String technologyId : technologyIds) {
            if (StrUtil.isBlank(technologyId)) {
                continue;
            }
            
            // 获取技术分类信息
            Genealogy genealogy = genealogyService.getById(technologyId);
            if (genealogy == null) {
                log.warn("技术分类不存在：{}", technologyId);
                continue;
            }
            
            // 查询该技术分类下的专利趋势
            TechnologyTrendVO trendVO = queryTrendDataByTechnology(genealogy, startYear, endYear);
            if (trendVO != null) {
                trendDataList.add(trendVO);
            }
        }
        
        return trendDataList;
    }

    /**
     * 查询单个技术分类的趋势数据
     */
    private TechnologyTrendVO queryTrendDataByTechnology(Genealogy genealogy, Integer startYear, Integer endYear) {
        try {
            TechnologyTrendVO trendVO = new TechnologyTrendVO();
            trendVO.setTechnologyId(genealogy.getId());
            trendVO.setTechnologyName(genealogy.getName());
            
            // 查询该技术分类关联的专利ID列表
            QueryWrapper<PatentGenealogy> pgWrapper = new QueryWrapper<>();
            pgWrapper.eq("genealogy_id", genealogy.getId());
            List<PatentGenealogy> patentGenealogyList = patentGenealogyService.list(pgWrapper);
            
            if (CollUtil.isEmpty(patentGenealogyList)) {
                trendVO.setTotalCount(0);
                trendVO.setYearDataList(createEmptyYearDataList(startYear, endYear));
                return trendVO;
            }
            
            List<String> patentIdList = patentGenealogyList.stream()
                    .map(PatentGenealogy::getPatentId)
                    .filter(StrUtil::isNotBlank)
                    .collect(Collectors.toList());
            
            if (CollUtil.isEmpty(patentIdList)) {
                trendVO.setTotalCount(0);
                trendVO.setYearDataList(createEmptyYearDataList(startYear, endYear));
                return trendVO;
            }
            
            // 查询专利按年份统计数据
            List<TechnologyTrendVO.YearDataVO> yearDataList = queryYearDataByPatentIds(patentIdList, startYear, endYear);
            trendVO.setYearDataList(yearDataList);
            
            // 计算总数量
            Integer totalCount = yearDataList.stream()
                    .mapToInt(TechnologyTrendVO.YearDataVO::getCount)
                    .sum();
            trendVO.setTotalCount(totalCount);
            
            return trendVO;
            
        } catch (Exception e) {
            log.error("查询技术分类{}的趋势数据失败", genealogy.getId(), e);
            return null;
        }
    }

    /**
     * 根据专利ID列表查询年度数据
     */
    private List<TechnologyTrendVO.YearDataVO> queryYearDataByPatentIds(List<String> patentIdList, 
                                                                        Integer startYear, 
                                                                        Integer endYear) {
        // 查询指定年份范围内的专利
        QueryWrapper<Patent> patentWrapper = new QueryWrapper<>();
        patentWrapper.in("id", patentIdList);
        patentWrapper.isNotNull("apply_date");
        patentWrapper.ge("YEAR(apply_date)", startYear);
        patentWrapper.le("YEAR(apply_date)", endYear);
        List<Patent> patentList = patentService.list(patentWrapper);
        
        // 按年份分组统计
        Map<Integer, Long> yearCountMap = patentList.stream()
                .filter(patent -> patent.getApplyDate() != null)
                .collect(Collectors.groupingBy(
                        patent -> DateUtil.year(patent.getApplyDate()),
                        Collectors.counting()
                ));
        
        // 生成完整的年度数据列表
        List<TechnologyTrendVO.YearDataVO> yearDataList = new ArrayList<>();
        Integer previousCount = null;
        
        for (int year = startYear; year <= endYear; year++) {
            TechnologyTrendVO.YearDataVO yearData = new TechnologyTrendVO.YearDataVO();
            yearData.setYear(year);
            
            Integer count = yearCountMap.getOrDefault(year, 0L).intValue();
            yearData.setCount(count);
            
            // 计算环比增长率
            if (previousCount != null && previousCount > 0) {
                double growthRate = ((double) (count - previousCount) / previousCount) * 100;
                yearData.setGrowthRate(new BigDecimal(growthRate).setScale(2, RoundingMode.HALF_UP).doubleValue());
            } else {
                yearData.setGrowthRate(0.0);
            }
            
            previousCount = count;
            yearDataList.add(yearData);
        }
        
        return yearDataList;
    }

    /**
     * 创建空的年度数据列表
     */
    private List<TechnologyTrendVO.YearDataVO> createEmptyYearDataList(Integer startYear, Integer endYear) {
        List<TechnologyTrendVO.YearDataVO> yearDataList = new ArrayList<>();
        
        for (int year = startYear; year <= endYear; year++) {
            TechnologyTrendVO.YearDataVO yearData = new TechnologyTrendVO.YearDataVO();
            yearData.setYear(year);
            yearData.setCount(0);
            yearData.setGrowthRate(0.0);
            yearDataList.add(yearData);
        }
        
        return yearDataList;
    }

    /**
     * 计算统计信息
     */
    private TrendQueryResultVO.StatisticsVO calculateStatistics(List<TechnologyTrendVO> trendDataList, 
                                                                Integer startYear, 
                                                                Integer endYear) {
        TrendQueryResultVO.StatisticsVO statisticsVO = new TrendQueryResultVO.StatisticsVO();
        
        if (CollUtil.isEmpty(trendDataList)) {
            statisticsVO.setTotalPatentCount(0);
            statisticsVO.setTechnologyCount(0);
            statisticsVO.setYearSpan(endYear - startYear + 1);
            statisticsVO.setMaxYearlyCount(0);
            statisticsVO.setAvgYearlyCount(0.0);
            return statisticsVO;
        }
        
        // 总专利数量
        Integer totalPatentCount = trendDataList.stream()
                .mapToInt(TechnologyTrendVO::getTotalCount)
                .sum();
        statisticsVO.setTotalPatentCount(totalPatentCount);
        
        // 技术分类数量
        statisticsVO.setTechnologyCount(trendDataList.size());
        
        // 年份跨度
        statisticsVO.setYearSpan(endYear - startYear + 1);
        
        // 最大年度申请量和平均年度申请量
        List<Integer> yearlyCountList = trendDataList.stream()
                .flatMap(trend -> trend.getYearDataList().stream())
                .map(TechnologyTrendVO.YearDataVO::getCount)
                .collect(Collectors.toList());
        
        if (CollUtil.isNotEmpty(yearlyCountList)) {
            Integer maxYearlyCount = yearlyCountList.stream().mapToInt(Integer::intValue).max().orElse(0);
            Double avgYearlyCount = yearlyCountList.stream().mapToInt(Integer::intValue).average().orElse(0.0);
            
            statisticsVO.setMaxYearlyCount(maxYearlyCount);
            statisticsVO.setAvgYearlyCount(new BigDecimal(avgYearlyCount).setScale(2, RoundingMode.HALF_UP).doubleValue());
        } else {
            statisticsVO.setMaxYearlyCount(0);
            statisticsVO.setAvgYearlyCount(0.0);
        }
        
        return statisticsVO;
    }

    /**
     * 将Genealogy转换为TechnologyDTO
     */
    private TechnologyDTO convertToTechnologyDTO(Genealogy genealogy) {
        if (genealogy == null) {
            return null;
        }
        
        TechnologyDTO technologyDTO = new TechnologyDTO();
        
        // ✅ 使用Hutool工具类复制相同的属性（符合@back.mdc规范）
        BeanUtil.copyProperties(genealogy, technologyDTO);
        
        // 手动处理字段名不同的属性
        technologyDTO.setParentId(genealogy.getPid());  // pid -> parentId
        
        // Genealogy中不存在的字段已经是null，无需单独设置
        
        return technologyDTO;
    }
}
